﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Linq;
using Microsoft.Office.Server.UserProfiles;
using System.Data;

namespace Trig_AMJ_IT_Customforms
{
    class Demand_Voucher_FormClass
    {
        /// <summary>
        /// Master Lists
        /// </summary>
        string SuppliersMaster = "Suppliers";
        string DivisionsMaster = "Divisions";
        string DepartmentsMaster = "Departments";
        string LocationsMaster = "Locations";
        string PaymentsModeMaster = "Payment Modes";

        SPQuery qry = null;

        public static string camlQry;

        ExceptionHandler exceptionHandler = new ExceptionHandler();

        ///Kannan Created 05-03-2013 V 1.0
        /// <summary>
        /// Get divisions master values and load into dropdownlist
        /// </summary>
        /// <param name="SiteUrl"></param>
        /// <param name="ddlDivisions"></param>
        public void GetDivisionsMaster(string SiteUrl, DropDownList ddlDivisions)
        {
            try
            {
                using (SPSite osite = new SPSite(SiteUrl))
                {
                    using (SPWeb oweb = osite.OpenWeb())
                    {
                        SPList DivList = oweb.Lists.TryGetList(DivisionsMaster);
                        if (DivList != null)
                        {
                            if (DivList.Items.Count > 0)
                            {
                                ddlDivisions.DataSource = DivList.Items.GetDataTable();
                                ddlDivisions.DataTextField = "Title";
                                ddlDivisions.DataValueField = "ID";
                                ddlDivisions.DataBind();
                            }
                        }
                        else
                        {
                            exceptionHandler.GenerateExceptionLog("Trig_AMJ_AMG_Forms::Demand_Voucher_FormClass::GetDivisionsMaster()", "List does not exist", DivisionsMaster + "List does not exist");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                exceptionHandler.GenerateExceptionLog("Trig_AMJ_IT_Forms::Demand_Voucher_FormClass::GetDivisionsMaster()", "Exception in catch block", ex.Message);
            }

        }


        ///Kannan Created 05-03-2013 V 1.0
        /// <summary>
        /// Get divisions master values and load into dropdownlist
        /// </summary>
        /// <param name="SiteUrl"></param>
        /// <param name="ddlDivisions"></param>
        public void GetDepartmentMaster(string SiteUrl, DropDownList ddlDepartments, string division)
        {
            ddlDepartments.Items.Clear();
            try
            {
                using (SPSite osite = new SPSite(SiteUrl))
                {
                    using (SPWeb oweb = osite.OpenWeb())
                    {
                        SPList DeptList = oweb.Lists.TryGetList(DepartmentsMaster);
                        if (DeptList != null)
                        {
                            qry = new SPQuery();
                            camlQry = "<Where><Eq><FieldRef Name=\"Division\" /><Value Type=\"Lookup\">" + division + "</Value></Eq></Where>";
                            qry.ViewFields = "<FieldRef Name=\"Title\" />";
                            SPListItemCollection oItemColl = null;
                            qry.Query = camlQry;
                            try
                            {
                                oItemColl = DeptList.GetItems(qry);
                            }
                            catch (Exception)
                            {
                                oItemColl = null;
                            }

                            if (oItemColl != null)
                            {
                                if (oItemColl.Count > 0)
                                {
                                    foreach (SPListItem oItem in oItemColl)
                                    {
                                        ddlDepartments.Items.Add(Convert.ToString(oItem["Title"]));
                                    }
                                    
                                }
                                
                            }

                        }
                        else
                        {
                            exceptionHandler.GenerateExceptionLog("Trig_AMJ_AMG_Forms::Demand_Voucher_FormClass::GetDepartmentMaster()", "List does not exist", DepartmentsMaster + "List does not exist");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                exceptionHandler.GenerateExceptionLog("Trig_AMJ_IT_Forms::Demand_Voucher_FormClass::GetDivisionsMaster()", "Exception in catch block", ex.Message);
            }

        }



        /// <summary>
        /// Get the supplier master values and load into dropdown list
        /// </summary>
        /// <param name="SiteUrl"></param>
        /// <param name="ddlSuppliers"></param>
        public void GetSupplierMaster(string SiteUrl, DropDownList ddlSuppliers)
        {
            try
            {
                using (SPSite osite = new SPSite(SiteUrl))
                {
                    using (SPWeb oweb = osite.OpenWeb())
                    {
                        SPList SupplierList = oweb.Lists.TryGetList(SuppliersMaster);
                        if (SupplierList != null)
                        {

                            if (SupplierList.Items.Count > 0)
                            {
                                ddlSuppliers.DataSource = SupplierList.Items.GetDataTable();
                                ddlSuppliers.DataTextField = "SupplierNameCode";
                                ddlSuppliers.DataValueField = "ID";
                                ddlSuppliers.DataBind();
                            }
                            ddlSuppliers.Items.Insert(0, "Select");
                        }
                        else
                        {
                            exceptionHandler.GenerateExceptionLog("Trig_AMJ_IT_Forms::Demand_Voucher_FormClass::GetSupplierMaster()", "List does not exist", SuppliersMaster + "List does not exist");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                exceptionHandler.GenerateExceptionLog("Trig_AMJ_IT_Forms::Demand_Voucher_FormClass::GetSupplierMaster()", "Exception in catch block", ex.Message);
            }

        }

        /// <summary>
        /// Get location master values and load into dropdownlist
        /// </summary>
        /// <param name="SiteUrl"></param>
        /// <param name="dllLocations"></param>
        public void GetLocationsMaster(string SiteUrl, DropDownList dllLocations)
        {
            try
            {
                using (SPSite osite = new SPSite(SiteUrl))
                {
                    using (SPWeb oweb = osite.OpenWeb())
                    {
                        SPList DivList = oweb.Lists.TryGetList(LocationsMaster);
                        if (DivList != null)
                        {
                            if (DivList.Items.Count > 0)
                            {
                                dllLocations.DataSource = DivList.Items.GetDataTable();
                                dllLocations.DataTextField = "Title";
                                dllLocations.DataValueField = "ID";
                                dllLocations.DataBind();
                            }
                        }
                        else
                        {
                            exceptionHandler.GenerateExceptionLog("Trig_AMJ_IT_Forms::Demand_Voucher_FormClass::GetLocationsMaster()", "List does not exist", LocationsMaster + "List does not exist");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                exceptionHandler.GenerateExceptionLog("Trig_AMJ_IT_Forms::Demand_Voucher_FormClass::GetLocationsMaster()", "Exception in catch block", ex.Message);
            }

        }


        /// <summary>
        /// Get Payment Modes Master values and load into dropdownlist
        /// </summary>
        /// <param name="SiteUrl"></param>
        /// <param name="ddlDivisions"></param>
        public void GetPaymentsModeMaster(string SiteUrl, DropDownList ddlDivisions)
        {
            try
            {
                using (SPSite osite = new SPSite(SiteUrl))
                {
                    using (SPWeb oweb = osite.OpenWeb())
                    {
                        SPList PayModeMaster = oweb.Lists.TryGetList(PaymentsModeMaster);
                        if (PayModeMaster != null)
                        {
                            if (PayModeMaster.Items.Count > 0)
                            {
                                ddlDivisions.DataSource = PayModeMaster.Items.GetDataTable();
                                ddlDivisions.DataTextField = "Title";
                                ddlDivisions.DataValueField = "ID";
                                ddlDivisions.DataBind();
                            }
                        }
                        else
                        {
                            exceptionHandler.GenerateExceptionLog("Trig_AMJ_IT_Forms::Demand_Voucher_FormClass::GetPaymentsModeMaster()", "List does not exist", PaymentsModeMaster + "List does not exist");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                exceptionHandler.GenerateExceptionLog("Trig_AMJ_IT_Forms::Demand_Voucher_FormClass::GetPaymentsModeMaster()", "Exception in catch block", ex.Message);
            }

        }

        /// <summary>
        /// Getting the Form reference number prefix and starting number
        /// </summary>
        /// <param name="rootWeb"></param>
        /// <param name="DocTypeListName"></param>
        /// <param name="oqryListname"></param>
        /// <returns></returns>
        public string[] getRefNum(string SiteUrl, string DocTypeListName, string oqryListname)
        {
            string[] RefNum = new string[2];
            try
            {
                //SPSecurity.RunWithElevatedPrivileges(delegate()
                //{
                using (SPSite FormSiteUrl = new SPSite(SiteUrl))
                {
                    using (SPWeb oweb = FormSiteUrl.OpenWeb())
                    {
                        SPList IDGenerationList = oweb.Lists.TryGetList(DocTypeListName);
                        if (IDGenerationList != null && !string.IsNullOrEmpty(oqryListname))
                        {
                            SPQuery orqy = new SPQuery();
                            orqy.Query = "<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + oqryListname + "</Value></Eq></Where>";
                            SPListItemCollection NumberItemCollection = IDGenerationList.GetItems(orqy);
                            if (NumberItemCollection.Count > 0)
                            {
                                SPListItem oitem = NumberItemCollection[0];
                                RefNum[0] = Convert.ToString(oitem["DocPrefix"]);
                                RefNum[1] = Convert.ToString(oitem["Starting_x0020_Number"]);
                            }
                        }
                        else
                        {
                            exceptionHandler.GenerateExceptionLog("Trig_AMJ_IT_Forms::Demand_Voucher_FormClass::getRefNum()()", "List does not exist", DocTypeListName + "List does not exist or Item does not exist in the the list (Document types)");
                        }
                    }
                }
                // });
            }
            catch (Exception ex)
            {
                exceptionHandler.GenerateExceptionLog("Trig_AMJ_IT_Forms::Demand_Voucher_FormClass::getRefNum()", "Exception in catch block", ex.Message);
            }
            return RefNum;
        }

        /// <summary>
        /// Generate reference number for demand voucher form
        /// </summary>
        /// <param name="rootWeb"></param>
        /// <param name="DocTypeListName"></param>
        /// <param name="oqryListname"></param>
        /// <returns></returns>
        public string[] RefNumberGeneration(SPWeb rootWeb, string DocTypeListName, string oqryListname)
        {
            string[] RefNo = new string[2];
            try
            {
                SPList DocumentTypesList = rootWeb.Lists.TryGetList(DocTypeListName);
                if (DocumentTypesList != null && !string.IsNullOrEmpty(oqryListname))
                {
                    SPQuery orqy = new SPQuery();
                    orqy.Query = "<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + oqryListname + "</Value></Eq></Where>";
                    SPListItemCollection NumberItemCollection = DocumentTypesList.GetItems(orqy);
                    if (NumberItemCollection.Count > 0)
                    {
                        SPListItem oitem = NumberItemCollection[0];
                        RefNo[0] = Convert.ToString(Convert.ToInt16(oitem["Starting_x0020_Number"]) + 1);
                        oitem["Starting_x0020_Number"] = RefNo[0];
                        RefNo[1] = Convert.ToString(oitem["DocPrefix"]);
                        rootWeb.AllowUnsafeUpdates = true;
                        oitem.Update();
                        rootWeb.AllowUnsafeUpdates = false;
                    }
                }
                else
                {
                    exceptionHandler.GenerateExceptionLog("Trig_AMJ_IT_Forms::Demand_Voucher_FormClass::RefNumberGeneration()", "List does not exist", DocTypeListName + "List does not exist or Item does not exist in the the list (Document types)");
                }
            }
            catch (Exception ex)
            {
                exceptionHandler.GenerateExceptionLog("Trig_AMJ_IT_Forms::Demand_Voucher_FormClass::RefNumberGeneration()", "Exception in catch block", ex.Message);
            }
            return RefNo;
        }

        /// <summary>
        /// Save the DV Workflow comments to respective comments list
        /// </summary>
        /// <param name="SiteUrl"> Forms site url</param>
        /// <param name="referenceNumber">Reference number for this item</param>
        public void SaveDVComments(string SiteUrl, string DemandVoucherComments, string referenceNumber, string UserComments, string ListID, int WFCurrentOrder)
        {
            try
            {
                if (!string.IsNullOrEmpty(UserComments))
                {
                    using (SPSite osite = new SPSite(SiteUrl))
                    {
                        using (SPWeb oweb = osite.OpenWeb())
                        {
                            SPList DVCommentsList = oweb.Lists.TryGetList(DemandVoucherComments);
                            if (DVCommentsList != null)
                            {
                                SPListItem CommentItem = DVCommentsList.Items.Add();
                                CommentItem["Reference_x0020_Number"] = referenceNumber;
                                CommentItem["CommentByUser"] = SPContext.Current.Web.CurrentUser.LoginName;
                                CommentItem["User_x0020_Comments"] = UserComments.Trim();
                                CommentItem["ListID"] = ListID;
                                CommentItem["WFCurrentOrder"] = WFCurrentOrder;
                                oweb.AllowUnsafeUpdates = true;
                                CommentItem.Update();
                                oweb.AllowUnsafeUpdates = false;

                            }
                            else
                            {
                                exceptionHandler.GenerateExceptionLog("Trig_AMJ_IT_Forms::Demand_Voucher_FormClass::SaveDVComments()", "List does not exist", DemandVoucherComments + "List does not exist ");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                exceptionHandler.GenerateExceptionLog("Trig_AMJ_IT_Forms::Demand_Voucher_FormClass::SaveDVComments()", "Exception in catch block", ex.Message);
            }

        }

        /// <summary>
        /// Upload attachment to Attachments library
        /// </summary>
        /// <param name="SiteUrl">Forms site url</param>
        /// <param name="AttachmentsLibrary">Library name</param>
        /// <param name="referenceNumber">Reference Number for this Item</param>
        /// <param name="FormListID">Form List Id</param>
        public void AddAttachement(string SiteUrl, string AttachmentsLibrary, string referenceNumber, string FormListID, FileUpload fileUploadControl)
        {
            try
            {
                using (SPSite osite = new SPSite(SiteUrl))
                {
                    using (SPWeb oweb = osite.OpenWeb())
                    {
                        SPDocumentLibrary myLibrary = oweb.Lists[AttachmentsLibrary] as SPDocumentLibrary;
                        if (myLibrary != null)
                        {
                            byte[] fileBytes = fileUploadControl.FileBytes;
                            string time = DateTime.Now.ToString().Replace("/", "");
                            string strDestUrl = myLibrary.RootFolder.Url + "/" + time.Replace(":", "") + fileUploadControl.FileName;
                            oweb.AllowUnsafeUpdates = true;
                            SPFile destFile = myLibrary.RootFolder.Files.Add(strDestUrl, fileBytes, true);
                            destFile.Item["ListID"] = FormListID;
                            destFile.Item["Reference_x0020_Number"] = referenceNumber;
                            SPUser ouser = oweb.EnsureUser(SPContext.Current.Web.CurrentUser.LoginName);
                            destFile.Item["UploadByUser"] = ouser;
                            destFile.Update();
                            destFile.Item.Update();
                            destFile.Update();
                            oweb.AllowUnsafeUpdates = false;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                exceptionHandler.GenerateExceptionLog("Trig_AMJ_IT_Forms::Demand_Voucher_FormClass::AddAttachement()", "Exception in catch block", ex.Message);
            }
        }

        /// <summary>
        /// check current user configured in the Workflow config list as a first item of the DV form
        /// </summary>
        /// <param name="oweb"></param>
        /// <returns></returns>
        public string[] CheckCurrentUserAsWFUser(SPWeb oweb, string WorkflowConfigList, string DemandVoucherFormsList, bool currentUserExist, string currentUser, bool approval, int WFCurrentOrder)
        {
            string[] orderNum = new string[10];
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    if (oweb.Lists.TryGetList(WorkflowConfigList) != null)
                    {
                        SPQuery oqry = new SPQuery();
                        if (currentUserExist)
                        {
                            oqry.Query = "<Where><And><Eq><FieldRef Name='Optional' /><Value Type='Boolean'>0</Value></Eq><And>"
                                + "<Neq><FieldRef Name='Send_x0020_to_x0020_Users' /><Value Type='User'>" + currentUser + "</Value></Neq><Eq><FieldRef Name='Doctype' />"
                                + "<Value Type='Lookup'>" + DemandVoucherFormsList + "</Value></Eq></And></And></Where>";
                        }
                        else if (approval)
                        {
                            oqry.Query = "<Where><And><Eq><FieldRef Name='Order0' /><Value Type='Number'>" + WFCurrentOrder + "</Value></Eq><Eq><FieldRef Name='Doctype' /><Value Type='Lookup'>" + DemandVoucherFormsList + "</Value></Eq></And></Where>";
                        }
                        else
                        {
                            oqry.Query = "<Where><Eq><FieldRef Name='Doctype' /><Value Type='Lookup'>" + DemandVoucherFormsList + "</Value></Eq></Where>";
                        }

                        if (oweb.Lists.TryGetList(WorkflowConfigList).GetItems(oqry).Count > 0)
                        {
                            SPListItem oitm = oweb.Lists.TryGetList(WorkflowConfigList).GetItems(oqry)[0];
                            orderNum[0] = Convert.ToString(oitm["Order0"]);
                            if (!string.IsNullOrEmpty(Convert.ToString(oitm["Send_x0020_to_x0020_Users"])))
                            {
                                SPFieldUserValue ofluser = new SPFieldUserValue(oweb, Convert.ToString(oitm["Send_x0020_to_x0020_Users"]));
                                orderNum[1] = ofluser.User.Name;
                            }
                            orderNum[2] = Convert.ToBoolean(oitm["Optional"]).ToString();
                            orderNum[3] = Convert.ToString(oitm["Task_x0020_type"]);
                            orderNum[4] = Convert.ToString(oitm["UPAttributeName"]);
                            orderNum[5] = Convert.ToString(oitm["ECListName"]);
                            orderNum[6] = Convert.ToString(oitm["ECFieldName"]);
                            orderNum[7] = Convert.ToString(oitm["ECMatchField"]);
                            orderNum[8] = Convert.ToString(oitm["ECUPMatchField"]);
                        }
                    }
                    else
                    {
                        exceptionHandler.GenerateExceptionLog("Trig_AMJ_IT_Forms::Demand_Voucher_FormClass::CheckCurrentUserAsWFUser()", "List does not exist", WorkflowConfigList + " List does not exist");
                    }
                });
            }
            catch (Exception ex)
            {
                exceptionHandler.GenerateExceptionLog("Trig_AMJ_IT_Forms::Demand_Voucher_FormClass::CheckCurrentUserAsWFUser()", "Exception in catch block", ex.Message);
            }

            return orderNum;

        }

        /// <summary>
        /// Get the profile picture of the user from SP User Profile
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public string GetUserProfilePictureURL(string username)
        {
            string Url = string.Empty;
            try
            {
                SPServiceContext serviceContext = SPServiceContext.GetContext(SPContext.Current.Site);
                UserProfileManager upm = new UserProfileManager(serviceContext);
                if (upm.UserExists(username))
                {
                    UserProfile profile = upm.GetUserProfile(username);
                    if (profile != null)
                    {
                        Url = profile["PictureURL"].Value.ToString();
                    }
                }

                //change it to the default if the user does not have an image specified
                if (string.IsNullOrEmpty(Url))
                    Url = "/_layouts/1033/IMAGES/PERSON.gif";
            }
            catch (Exception ex)
            {
                exceptionHandler.GenerateExceptionLog("Trig_AMJ_IT_Forms::Demand_Voucher_FormClass::GetUserProfilePictureURL()", "Exception in catch block", ex.Message);
            }


            return Url;
        }

        /// <summary>
        /// get current user division name
        /// </summary>
        /// <param name="SiteUrl"></param>
        /// <param name="dllLocations"></param>
        public string GetcurrentUserDivisionName(string currentUserName)
        {
            string userDivision = string.Empty;
            try
            {
                SPServiceContext serviceContext = SPServiceContext.GetContext(SPContext.Current.Site);
                UserProfileManager upm = new UserProfileManager(serviceContext);
                if (upm.UserExists(currentUserName))
                {
                    UserProfile profile = upm.GetUserProfile(currentUserName);
                    if (profile != null)
                    {
                        userDivision = profile["Division"].Value.ToString();
                    }
                    else
                    {
                        exceptionHandler.GenerateExceptionLog("Trig_AMJ_IT_Forms::Demand_Voucher_FormClass::GetcurrentUserDivisionName()", "UserProfile value is empty", "Division property value is empty");
                    }
                }

            }
            catch (Exception ex)
            {
                exceptionHandler.GenerateExceptionLog("Trig_AMJ_IT_Forms::Demand_Voucher_FormClass::GetcurrentUserDivisionName()", "Exception in catch block", ex.Message);
            }

            return userDivision;
        }

        /// <summary>
        /// get the forward button visibility
        /// </summary>
        /// <param name="oweb"></param>
        /// <param name="wfConfigListName"></param>
        /// <param name="FormListName"></param>
        /// <param name="WFOrder"></param>
        /// <returns></returns>
        public string[] getForwardbuttonVisibility(string forSiteUrl, string wfConfigListName, string FormListName, int WFOrder)
        {
            string[] buttonVisibility = new string[5];
            try
            {
                using (SPSite frmSite = new SPSite(forSiteUrl))
                {
                    using (SPWeb frmWeb = frmSite.OpenWeb())
                    {
                        SPList wfConfigList = frmWeb.Lists.TryGetList(wfConfigListName);
                        if (wfConfigList != null)
                        {
                            SPQuery oqry = new SPQuery();
                            oqry.Query = "<Where><And><Eq><FieldRef Name='Order0' /><Value Type='Number'>" + WFOrder + "</Value></Eq><Eq><FieldRef Name='Doctype' /><Value Type='Lookup'>" + FormListName + "</Value></Eq></And></Where>";
                            if (wfConfigList.GetItems(oqry).Count > 0)
                            {
                                SPListItem oitm = wfConfigList.GetItems(oqry)[0];
                                buttonVisibility[0] = Convert.ToString(oitm["Send_x0020_Back"]);
                                buttonVisibility[1] = Convert.ToString(oitm["Forward_x0020_to_x0020_other_x00"]);
                                buttonVisibility[2] = Convert.ToString(oitm["Forward"]);
                                buttonVisibility[3] = Convert.ToString(oitm["CanApproveReject"]);
                                buttonVisibility[4] = Convert.ToString(oitm["Can_x0020_add_x0020_comments_x00"]);
                            }
                        }
                        else
                        {
                            exceptionHandler.GenerateExceptionLog("Trig_AMJ_IT_Forms::Demand_Voucher_FormClass::getForwardbuttonVisibility()", "List does not exist", wfConfigListName + " List does not exist");
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                exceptionHandler.GenerateExceptionLog("Trig_AMJ_AMG_Forms::Demand_Voucher_FormClass::getForwardbuttonVisibility()", "Exception in catch block", ex.Message);
            }
            return buttonVisibility;
        }

        /// <summary>
        /// SEnd back the WF to user
        /// </summary>
        /// <param name="siteUrl"></param>
        /// <param name="taskList"></param>
        /// <param name="taskItemID"></param>
        /// <param name="RefNO"></param>
        /// <returns></returns>
        public SPFieldUserValue getSendBackUserfNametoAssignLabelText(string siteUrl, string taskList, int taskItemID, string RefNO, RadioButton rtbForwordControl, RadioButton rtbForwordonly, Label lblErrormsg)
        {
            SPFieldUserValue ofldval = null;
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    if (taskItemID.ToString() != null)
                    {
                        using (SPSite formSite = new SPSite(siteUrl))
                        {
                            using (SPWeb oweb = formSite.OpenWeb())
                            {
                                SPQuery oqy = new SPQuery();
                                oqy.Query = "<Where><And><Eq><FieldRef Name='Reference_x0020_Number' /><Value Type='Text'>" + RefNO + "</Value></Eq><Eq><FieldRef Name='Status' /><Value Type='Choice'>Completed</Value></Eq></And></Where><OrderBy><FieldRef Name='ID' Ascending='False' /></OrderBy>";
                                if (oweb.Lists.TryGetList(taskList) != null)
                                {
                                    if (oweb.Lists.TryGetList(taskList).GetItems(oqy).Count > 0)
                                    {
                                        SPListItem oitm = oweb.Lists.TryGetList(taskList).GetItems(oqy)[0];
                                        ofldval = new SPFieldUserValue(oweb, Convert.ToString(oitm["AssignedTo"]));
                                        lblErrormsg.Visible = false;
                                    }
                                    else
                                    {
                                        lblErrormsg.Visible = true;
                                        lblErrormsg.Text = "Can't be send back. User is not available";
                                        rtbForwordonly.Visible = true;
                                    }

                                }
                            }
                        }

                    }
                });
            }
            catch (Exception ex)
            {
                exceptionHandler.GenerateExceptionLog("Trig_AMJ_IT_Forms::Demand_Voucher_FormClass::getSendBackUserfNametoAssignLabelText()", "Exception in catch block", ex.Message);
            }

            return ofldval;
        }

        /// <summary>
        /// Update the form Status
        /// </summary>
        /// <param name="frmWeb"></param>
        /// <param name="FrmListName"></param>
        /// <param name="referenceNumber"></param>
        public void UpdateFormStatus(SPWeb frmWeb, string WFConfigList, string FrmListName, string referenceNumber, int WFcurrentOrder, bool reject)
        {
            try
            {
                SPList frmList = frmWeb.Lists.TryGetList(FrmListName);
                if (frmList != null)
                {
                    SPQuery oqry = new SPQuery();
                    oqry.Query = "<Where><Eq><FieldRef Name='Reference_x0020_Number' /><Value Type='Text'>" + referenceNumber + "</Value></Eq></Where>";
                    if (frmList.GetItems(oqry).Count > 0)
                    {
                        SPListItem oitm = frmList.GetItems(oqry)[0];
                        if (reject)
                        {
                            oitm["Document_x0020_Status"] = "Rejected";
                        }
                        else
                        {
                            string[] count = CheckWFCount(frmWeb, WFConfigList, FrmListName);
                            if (Convert.ToInt32(count[0]) == WFcurrentOrder)
                            {
                                oitm["Document_x0020_Status"] = "Approved";
                            }
                            else
                            {
                                oitm["Document_x0020_Status"] = "In Progress";
                            }
                        }
                        frmWeb.AllowUnsafeUpdates = true;
                        oitm.Update();
                        frmWeb.AllowUnsafeUpdates = false;
                    }

                }
            }
            catch (Exception ex)
            {
                exceptionHandler.GenerateExceptionLog("Trig_AMJ_IT_Forms::Demand_Voucher_FormClass::UpdateFormStatus()", "Exception in catch block", ex.Message);
            }
        }
        /// <summary>
        /// Check the Workflow count
        /// </summary>
        /// <param name="frmWeb"></param>
        /// <param name="WFConfigList"></param>
        /// <param name="FrmListName"></param>
        /// <returns></returns>
        public string[] CheckWFCount(SPWeb frmWeb, string WFConfigList, string FrmListName)
        {
            string[] count = new string[2];
            try
            {
                SPList wfConfigList = frmWeb.Lists.TryGetList(WFConfigList);
                if (wfConfigList != null)
                {
                    SPQuery oqry = new SPQuery();
                    oqry.Query = "<Where><Eq><FieldRef Name='Doctype' /><Value Type='Lookup'>" + FrmListName + "</Value></Eq></Where>";
                    count[0] = wfConfigList.GetItems(oqry).Count.ToString();
                    SPFieldUserValue ofld = new SPFieldUserValue(frmWeb, Convert.ToString(wfConfigList.GetItems(oqry)[0]["Send_x0020_to_x0020_Users"]));
                    count[1] = ofld.User.Name;
                }
            }
            catch (Exception ex)
            {
                exceptionHandler.GenerateExceptionLog("Trig_AMJ_IT_Forms::Demand_Voucher_FormClass::CheckWFCount()", "Exception in catch block", ex.Message);
            }

            return count;
        }
    }
}

